import React, { useEffect, useState, useMemo, useRef, forwardRef, useReducer } from 'react';
import {
  Switch,
  Route,
  withRouter,
  useHistory,
  Link,
} from "react-router-dom";
import classNames from 'classnames';
import { RawBtn } from '../components/Btn';
import { StandardBleConnector } from '../StandardBleDemo/components/StandardBleConnector';
import {InputUserPage} from './InputUserPage';
import {CklsPage} from './CklsPage';
import {SjfxPage} from './SjfxPage';
import {DeviceDetail} from './DeviceDetail';
import {DbfxPage} from './DbfxPage';
import {Version} from './Version';
import sdk from 'qcloud-iotexplorer-h5-panel-sdk';
import { useDeviceData } from '../hooks/useDeviceData';
import PubSub from 'pubsub-js' //引入
import moment from 'moment';
import './Jkcard.less';
import { Toast} from 'antd-mobile';
import { IMGURL,APIURL,APPID,APPSECRET } from '../utils/common';
const thirdUserNo = "para_user1"
const c_type = 1
// 当前时间
const windowHeight = window.innerHeight || document.documentElement.clientHeight;
let myuserInfo = sdk.userInfo 
// 目标体重
const mbweight = 68.00
let LayoutRouter  = () => (
  <div>
  <Switch>
      <Route path="/Home" exact><Home /></Route>
      <Route path="/PanelPage" exact><PanelPage /></Route>
      <Route path="/CklsPage" exact><CklsPage /></Route>
      <Route path="/home" exact><PanelPage /></Route>
      <Route path="/InputUserPage" exact ><InputUserPage  isinput={true}/></Route>
      <Route path="/DbfxPage" exact><DbfxPage /></Route>
      <Route path="/SjfxPage" exact><SjfxPage /></Route>
      <Route path="/Yystspage" exact><Yystspage /></Route>
      <Route path="/DeviceDetail" exact><DeviceDetail /></Route>
      <Route path="/"><Home /></Route>
  </Switch>
  </div>
);
export function Jkcard(props) {
  const [sdkReady, setSdkReady] = useState(false);
  useEffect(() =>  {
      h5PanelSdk.sdkReady().then(() =>  setSdkReady(true));
  }, []);
  return !sdkReady ? <div > loading...</div >  : (
    <div>
     <LayoutRouter/>
    </div>
  )
}
function Home(props) {
  const history = useHistory()
  let jxstate =null
  // let jxstate ={
  //   "battery_status":85,
  //   "weight_unit":2,
  //   "weight":63.3689,
  //   "body_r_enc":45623.36,
  //   "stable_data_flag":1
  // }
  if ( history.location.state !=null ) {
    jxstate = history.location.state || null
    console.error("----------")
    console.error(jxstate)
  }
  // useDeviceData包含以下值，deviceData，deviceStatus，templateMap，templateList
  const [state, {onDeviceDataChange,onDeviceStatusChange}] = useDeviceData(sdk);
  // 身体数据
  const [bodyInfo, setbodyInfo] = useState(null);
  // 从云端获取到的属性枚举值
  const wulist =state.templateMap.weight_unit.define.mapping
  const unitindex = state.deviceData.weight_unit
  // 根据单位显示体重
  const [iweight,setiweight] = useState("0.00")
  const [iweight_unit,setiweight_unit] = useState(0)
  // WebSocket 监听
  useEffect(() => {
    // 监听设备控制推送
    const handleWsControl = ({ deviceId, deviceData }) => {
      if (deviceId === sdk.deviceId) {
        onDeviceDataChange(deviceData);
      }
      console.log('Jkcard wsControl', deviceData);
    };
    // 监听设备上报数据推送
    const handleWsReport = ({ deviceId, deviceData }) => {
      if (deviceId === sdk.deviceId) {
        onDeviceDataChange(deviceData);
      }
      console.log('Jkcard wsReport', deviceId, deviceData);
    };
    // 监听设备在线状态变更推送
    const handleWsStatusChange = ({ deviceId, deviceStatus}) => {
      if (deviceId === sdk.deviceId) {
        onDeviceStatusChange(deviceStatus);
      }
      console.log('Jkcard wsStatusChange', deviceId, deviceStatus );
    };

    sdk
      .on('wsControl', handleWsControl)
      .on('wsReport', handleWsReport)
      .on('wsStatusChange', handleWsStatusChange);

    return () => {
      sdk
        .off('wsControl', handleWsControl)
        .off('wsReport', handleWsReport)
        .off('wsStatusChange', handleWsStatusChange);
    };
  }, []);
  // 检查固件更新
  useEffect(() => {
    // 检查固件更新，若有可升级固件，且设备在线，则弹出提示
    const doCheckFirmwareUpgrade = async () => {
      try {
        const upgradeInfo = await sdk.checkFirmwareUpgrade({
          silent: true, // 设置为 true 则只检查，不弹出提示
        }).then(({ CurrentVersion, DstVersion }) => {
          if (DstVersion && CurrentVersion !== DstVersion) {
           // 开发者需要在此处实现自定义的固件升级提示的展示
           Toast.info('发现新的固件版本，请手动升级！', 2)
          }
          sdk.blueToothAdapter.reportDeviceInfo(
            { 
              productId: sdk.productId, 
              deviceName: sdk.deviceName, 
              deviceInfo: {
                // "module_hardinfo": "模组具体硬件型号 N10",
                "module_softinfo": CurrentVersion,
              } 
            }
          )
        });
        console.log('firmware upgrade info', upgradeInfo);
      } catch (err) {
        console.error('checkFirmwareUpgrade fail', err);
      }
    };
    doCheckFirmwareUpgrade();
    
    
  }, []);
  // 首次加载获取数据
  useMemo(() => {
    signature()
    // 首次加载读取，若无数据自动录入数据库
    getLastUserData()
    PubSub.subscribe('third_user',(msg, pubsubTest) => {
      // getThirdUserInfo(pubsubTest.id)
      getThirdUserInfo(pubsubTest.id).then(function onFulfilled(value){
        if(value.height == null || value.birthday == null || value.height == "" || value.birthday == ""){
          // 用户信息为空,props.
          Toast.fail('用户信息不完整，无法计算体脂！请先录入数据！', 3)
          jxstate ={
            body_r_enc:0,
            weight:60,
            weight_unit:0,
            stable_data_flag:1
          }
          // history.push("/InputUserPage")
        }
      }).catch(function onRejected(error){
        console.log('错误：' + error); 
      });
      PubSub.unsubscribe("third_user");
    })
  }, [])
  useEffect(() => {
    let third_user = {}
    PubSub.subscribe('third_user',(msg, pubsubTest) => {
      third_user = pubsubTest
      PubSub.unsubscribe("third_user");
    })
    // jxstate=蓝牙传输过来的数据(计算后的结果)
    if(jxstate!= null && Object.keys(jxstate).length > 0 && jxstate.weight != undefined && parseInt(jxstate.weight) > 0){
      // 过滤非正常阻抗
      let tempbody_r_enc = 0
      tempbody_r_enc = jxstate.body_r_enc== null || jxstate.body_r_enc < 1 ? 0 : parseInt(jxstate.body_r_enc)
      // parseFloat(jxstate.weight).toFixed(2) 不用截取
      // jxstate.weight = jxstate.weight!= null || jxstate.weight!= undefined  ? jxstate.weight : 0
      // 首页获取显示
      let tempweight = 0
      tempweight =  jxstate.weight!= null || jxstate.weight!= undefined ? parseFloat(jxstate.weight).toFixed(2) : 0
      // if(parseInt(jxstate.weight_unit) == 1){
      //   tempweight =  jxstate.weight!= null || jxstate.weight!= undefined  ? (jxstate.weight / 2.20460 ).toFixed(2) : 0
      // }else{
      //   tempweight =  jxstate.weight!= null || jxstate.weight!= undefined ? jxstate.weight : 0
      // }
      PubSub.subscribe('third_user',(msg, pubsubTest) => {
        if(third_user.height == null || third_user.birthday == null || third_user.height == "" || third_user.birthday == ""){
          third_user.height = 160
          third_user.birthday = current_time
        }
        getlastbdinfo(third_user,"C0D619461F400808256806487E4ED3")
        PubSub.unsubscribe("third_user");
      })
      PubSub.subscribe('lefuData',(msg, pubsubTest) => {
        if(Object.keys(pubsubTest).length!=0){
          setbodyInfo(pubsubTest)
          // 重组乐福数据数据
          getbdinfo(third_user,pubsubTest,jxstate,wulist)
        }
        //取消订阅
        PubSub.unsubscribe("lefuData");
      })
      PubSub.subscribe('bdinfoarry',(msg, pubsubTest) => {
        if(Object.keys(pubsubTest).length!=0){
          // 存储体脂数据
          addThirdUserData(pubsubTest)
        }
        //取消订阅
        PubSub.unsubscribe("bdinfoarry");
      })
      // 计算后的蓝牙数据
      const weightdata = forunit(tempweight,jxstate.weight_unit)
      setiweight(weightdata.weight)
      setiweight_unit(weightdata.weight_unit)
    }else{
      getThirdUserData()
      PubSub.subscribe('lastuserData',(msg, pubsubTest) => {
        if(Object.keys(pubsubTest).length!=0){
          // 计算后的蓝牙数据
          const weightdata = forunit(pubsubTest.user_weight,pubsubTest.user_weight_u)
          setiweight(weightdata.weight)
          setiweight_unit(weightdata.weight_unit)
          // setiweight(pubsubTest.user_weight)
          // setiweight_unit(wulist[pubsubTest.user_weight_u])
          // 首页获取显示
          // if(parseInt(pubsubTest.user_weight_u) == 1){
          //   pubsubTest.user_weight = ( pubsubTest.user_weight / 2.20460 ).toFixed(2)
          // }
          console.log('jxstate3' + pubsubTest.user_weight); 
          console.log('weightdata'); 
          // console.log(weightdata); 
          getlastbdinfo(third_user,"C0D619461F400808256806487E4ED3")
          PubSub.subscribe('lefuData',(msg, pubsubTest) => {
            if(Object.keys(pubsubTest).length!=0){
              setbodyInfo(pubsubTest)
            }
            PubSub.unsubscribe("lefuData");//取消订阅
          })
        }
        PubSub.unsubscribe("lastuserData");//取消订阅
      })
    }
  }, [jxstate])
  function showzl(){
    history.location.state = null
    jxstate = null
    console.error(jxstate)
    console.error(history.location.state)
    history.push('/Yystspage')
  }
  const showDeviceDetail =()=>{
    history.location.state = null
    jxstate = null
    console.error(jxstate)
    console.error(history.location.state)
    history.replace("/DeviceDetail")
  }
  return (
    <div className="device-panel clear-margin"  style={{ minHeight: `${windowHeight}px` }}>
      <div>
        <div className="fl-rr">
        {/* <DeviceDetailBtn /> */}
        <RawBtn
          className="panel-more-btn"
          onClick={showDeviceDetail}
        >
          <div className="more-btn-icon" />
        </RawBtn>
        </div>
        <div className="jkcardpage">
          {/* <div className="floatbtn" onClick={showzl}>
          <img src={IMGURL+"home_btn_contact_n@3x.png"}/>
          </div> */}
          <div className="jkcon">
            {/* 健康card */}
            <div className="jkcard mgb">
            <div className="fl-cc wcolor">
              <div className="fl-rc weightinfo textcolor">
                <div className="weight fl-cc">
                  {/* 处理后的单位和体重 */}
                  <div className="wnum mgb">
                    {iweight}<span className="ttext">{wulist[iweight_unit]}</span>
                  </div>
                  <div className="tittext">体重：<span className="gc">{bodyInfo!=null ? bodyInfo[0].level : "标准"}</span></div>
                </div>
              </div>
              <div className="fl-rc tipstext">
                <img src={IMGURL+"site.png"}/>
              </div>
              <div className="fl-rc">
                {/* replace */}
                <Link to="/PanelPage" replace>
                <span className="lfbtn"><img src={IMGURL+"btn_cz.png"}/>测量</span>
                </Link>
              </div>
            </div>
            </div>
          </div>
          {/* 测量数据 */}
          <div className="textcolor mgb fl-rsbc">
            <div className="tittext">测量数据</div>
            <div className="ttext"><Link to={{ pathname:'/CklsPage',state : { pagename : 'chakan',unit : unitindex }}} className="textcolor" replace> 查看历史</Link></div>
          </div>
          {bodyInfo == undefined ? <div className="textcolor mgtb">暂无数据，请连接体脂秤！</div> :
          <>
          <div className="cssj mgb">
            {bodyInfo.length == 0 ? "暂无数据！" : <Biminfocard biminfo={bodyInfo[4]}/>}
          </div>
          <div className="jkcardlist">
            {bodyInfo.length == 0 ? "暂无数据！" : <BodyInfocard bodyInfo={bodyInfo} weight_unit={iweight_unit} wulist={wulist}/>}
          </div>
          </>
          }
          {/* 数据对比 */}
          <div className="textcolor mgb fl-c">
            <div className="tittext">数据对比</div>
            <div className="ttext mgt5">选择您的两次测量数据，对其变化进行比对</div>
          </div>
          <div className="bd1 sjdbimg pdb">
            <Link  to={{ pathname:'/CklsPage',state:{pagename:'duibi'}}} replace>
              <img src={IMGURL+"db.png"}/>
            </Link>
          </div>
          <div className="pdtb tc gc fl-rc kfxx">
            <img src={IMGURL+"phone.png"}/>客服电话: 400-6035- -688
          </div>
        </div>
      </div>
      <Version/>
    </div>
  );
}
// 营养师提示
function Yystspage(){
  const history = useHistory()
  function closeed(){
    history.replace('/Home')
  }
  return(
    <div className="showShade">
 			<div className="showShadecon">
 				<div className="Yystspage wcolor fl-cc">
           <div className="closebtn" onClick={closeed}>X</div>
            <div className="tittext mgb">已将营养师的微信号</div>
            <div className="numtext pcolor mgb">13336330303</div>
            <div className="tc mgb pd tipstext">复制到您的剪切板当中，请您到微信中 添加营养师为好友进行健康咨询！</div>
            <div className="lfbtn-g">去咨询</div>
          </div>
 			</div>
 		</div>
  )
} 
export function PanelPage() {
  const isStandardBleDevice = sdk.isStandardBleDevice;
	return (
		<div className="bluetooth-panel bdwhite" style={{ minHeight: `${windowHeight}px` }}>
      <div  className="fl-cc">
          {isStandardBleDevice && (
            <StandardBleConnector familyId={sdk.familyId} deviceId={sdk.deviceId} />
          )}
      </div>
		</div>
	)
}
export default withRouter(Yystspage)
export function Bzbgcolor(props){
  const level = props.level
  if( level== "偏低" || level== "偏瘦" || level== "偏轻"|| level== "偏瘦型"){return <span className="zsbgcolor wstate ">{level}</span>}
  else if( level== "偏高"){return  <span className="pgbgcolor wstate ">{level}</span>}
  else if( level== "标准" || level== "健康"){return  <span className="psbgcolor wstate ">{level}</span>}
  else if( level== "不足"){return  <span className="bzbgcolor wstate ">{level}</span>}
  else if( level== "肥胖"){return  <span className="zdbgcolor wstate ">{level}</span>}
  else if( level== ""){return  ""}
  else {return <span className="psbgcolor wstate">{level}</span>}
}
// bimcard组件
function Biminfocard(props){
  let biminfo = props.biminfo
  return(
    <div className="cssjcard psbgcolor wcolor pd fl-rsbc">
        <div className="fl-cc cssjtit">
          <div>{biminfo.name}</div>
          <div>{biminfo.num}</div>
        </div>
        <div className="cssjrcon">
          <div className="tr mgb"><span className="bzstate">{biminfo.level}</span></div>
          <div className="prog tsize">
            <Bimlevel iStand={biminfo.levelStand} num={biminfo.num} level={biminfo.level}/>
          </div>
        </div>
    </div>
  )
}
function Bimlevel(props){
  const levellist = ["偏瘦","标准","偏胖","胖"]
  let iStand = props.iStand
  let num = props.num
  let level = levellist.indexOf(props.level)
  // let level = 0      // 数组去重
  function unique (arr) {
    return Array.from(new Set(arr))
  }
  useMemo(()=>{
    if(iStand.length > 0){
      iStand.unshift(0)
    }
    iStand = unique(iStand)
  },[])
  return(
    <>
    {iStand.length == 0 ? "暂无数据！" :
    <div>
    <div className="prog-tit">
      {levellist.map((item,index)=>{return <span key={index}>{item}</span>})}
    </div>

    <div className="prog-bar mgtb">
      {iStand.map(function(item,index){return <span key={index} className={classNames({"selected": item <= num},{"lastchild": level == index})}></span>})}
    </div>
    <div className="prog-desc">
      {iStand.map(function(item,index){return <span key={index}>{item}</span>})}
    </div>
    </div>
    }
    </>
  )
}
// 体脂数据card组件
function BodyInfocard(props){
  // let bodyInfo = props.bodyInfo
  // let weight_unit = props.weight_unit
  // wulist
  let {bodyInfo,weight_unit,wulist} = props
  return(
    bodyInfo.map((item,index)=>{
        return (
          <div className="jkinfocard mgb textcolor fl-cc pd" key={index}>
            <div className="numtext">
              {item.name=="体重" ? forunit(item.num,weight_unit).weight : item.num}
            </div>
            {/* && weight_unit=="LB" ? */}
            <div className="ttext mgtb">{item.name}
              {item.name=="体重" ? "("+wulist[weight_unit]+")" : item.unit}
            </div>
            <div className={classNames({'displyn':item.level==""})}>
              {item.level!="" &&<Bzbgcolor level={item.level}/>}
            </div>
          </div>
        )
      }
    )        
  )
}
// 体重card
function WeightInfocard(props){
  let bodyInfo = props.bodyInfo
  return(
    <div></div>      
  )
}
// 根据生日算年龄
const matAge=(bir,c_time)=>{
	var age = Math.ceil((c_time-bir)/31536000000);
	return age
}
// 处理单位
const forunit=(weight,weight_unit)=>{
  // console.error(weight,weight_unit)
	let tbleMessage = {
		weight:0,weight_unit:0
	}
  let tweight = 0
	switch(parseInt(weight_unit)){
    case 0:
      tbleMessage.weight = parseFloat(weight).toFixed(2)
      tbleMessage.weight_unit = parseInt(weight_unit)
      return tbleMessage
    case 1:
      tweight = parseFloat(weight).toFixed(1)*2.20460
      tweight = weight <= 0 ? 0 : formatDecimal(tweight,1)
      tbleMessage.weight = tweight
      tbleMessage.weight_unit = parseInt(weight_unit)
      return tbleMessage
    case 3:
      tweight = parseFloat(weight).toFixed(2)*2
      tweight = weight <= 0 ? 0 : formatDecimal(tweight,1)
      tbleMessage.weight = tweight
      tbleMessage.weight_unit = parseInt(weight_unit)
      return tbleMessage
    // default:
    //   tbleMessage.weight = 0.0
    //   tbleMessage.weight_unit = 0
    //   return tbleMessage
  }
}
// 添加体脂数据
const addThirdUserData =(bdinfo) =>{
  var request = require('superAgent')
  request
  .post(APIURL+'addThirdUserData')
  .send(bdinfo)
  .end(function(err, res){
    if(res.body.code == 1){
      Toast.success("更新成功！")
    }else{
      console.log('服务器出错'+res)
      Toast.fail(res.body.msg)
    }
  })
}
// 获取最新的用户基本信息
const getLastUserData =() =>{
  var request = require('superAgent')
  request
  .post(APIURL+'getlastuserinfo_tx')
  .send({
    "productId":sdk.productId,
    "deviceName":sdk.deviceName,
    "wx_unionid":myuserInfo.UserID,
    "username":myuserInfo.NickName,
    "userimg":myuserInfo.Avatar,
  })
  // .set('Content-Type', 'application/text')
  .end(function(err, res){
    if(res.body.code == 1){
      var JkcardUdata = res.body.data.third_user
      console.log('获取最新的用户数据',JkcardUdata)
      PubSub.publish('third_user',JkcardUdata)
    }else{
      console.log('服务器'+res)
    }
  })
}
// 存储的历史用户数据
const getThirdUserData =() =>{
  var request = require('superAgent')
  request
  .post(APIURL+'getThirdUserData_structure')
  .send({
  "productId":sdk.productId,
  "deviceName":sdk.deviceName,
  "thirdUserNo":thirdUserNo,
  "wx_unionid":myuserInfo.UserID,
  "pageNo":1,
  "pageSize":10,
  })
  .end(function(err, res){
    console.log('存储的历史用户数据1',res)
    if(res.body.code == 1){
      var _arry = []
      var JkcardUdata = res.body.data.data
      if (JkcardUdata.length > 0){
        JkcardUdata = JkcardUdata.reverse()
        console.log('存储的历史用户数据1',JkcardUdata)
        if (JkcardUdata.length != 0){
          PubSub.publish('lastuserData',((JkcardUdata[0].user_data).reverse())[0])
        }
        console.log('存储的历史用户数据2',((JkcardUdata[0].user_data).reverse())[0])
      }
    }else{
      console.log('服务器'+res)
    }
  })
}
const current_time = (new Date()).valueOf()
// 首次获取乐福接口数据---并入库
function getbdinfo(userinfo,bdinfo,jxstate,wulist){
  const weightdata = forunit(jxstate,wulist)
  if(bdinfo != null && Object.keys(bdinfo).length > 0){
    console.log("获取乐福接口数据---入库")
    console.log(bdinfo)
    var bdinfoarry = {}
    for(let index in bdinfo) {
      // 重组数据
      switch(bdinfo[index].name){
        case "体重":
          // bdinfoarry.user_weight=bdinfo[index].num
          bdinfoarry.user_weight_r=bdinfo[index].level
          // bdinfoarry.user_weight_u=bdinfo[index].unit
        break;
        case "BMI":
          bdinfoarry.bmi=bdinfo[index].num
          bdinfoarry.bmi_r=bdinfo[index].level
          bdinfoarry.bmi_u=bdinfo[index].unit
        break;
        case "BMR":
          bdinfoarry.bmr=bdinfo[index].num
          bdinfoarry.bmr_r=bdinfo[index].level
          bdinfoarry.bmr_u=bdinfo[index].unit
        break;
        case "体脂率":
          bdinfoarry.body_fat_per=bdinfo[index].num
          bdinfoarry.body_fat_per_r=bdinfo[index].level
          bdinfoarry.body_fat_per_u=bdinfo[index].unit
        break;
        case "骨量":
          bdinfoarry.bone=bdinfo[index].num
          bdinfoarry.bone_r=bdinfo[index].level
          bdinfoarry.bone_u=bdinfo[index].unit
        break;
        case "肌肉量":
          bdinfoarry.muscle=bdinfo[index].num
          bdinfoarry.muscle_r=bdinfo[index].level
          bdinfoarry.muscle_u=bdinfo[index].unit
        break;
        case "体水分率":
          bdinfoarry.bodywater=bdinfo[index].num
          bdinfoarry.bodywater_r=bdinfo[index].level
          bdinfoarry.bodywater_u=bdinfo[index].unit
        break;
        case "内脏脂肪":
          bdinfoarry.visceral_fat=bdinfo[index].num
          bdinfoarry.visceral_fat_r=bdinfo[index].level
          bdinfoarry.visceral_fat_u=bdinfo[index].unit
        break;
        case "蛋白质":
          bdinfoarry.protein=bdinfo[index].num
          bdinfoarry.protein_r=bdinfo[index].level
          bdinfoarry.protein_u=bdinfo[index].unit
        break;
        case "皮下脂肪率":
          bdinfoarry.subskin_fat=bdinfo[index].num
          bdinfoarry.subskin_fat_r=bdinfo[index].level
          bdinfoarry.subskin_fat_u=bdinfo[index].unit
        break;
        case "肥胖等级":
          bdinfoarry.obesity_level=bdinfo[index].num
          bdinfoarry.obesity_level_r=bdinfo[index].level
          bdinfoarry.obesity_level_u=bdinfo[index].unit
        break;
        case "去脂体重":
          bdinfoarry.ffm=bdinfo[index].num
          bdinfoarry.ffm_r=bdinfo[index].level
          bdinfoarry.ffm_u=bdinfo[index].unit
        break;
        case "身体类型":
          bdinfoarry.body_type=bdinfo[index].num
          bdinfoarry.body_type_r=bdinfo[index].level
          bdinfoarry.body_type_u=bdinfo[index].unit
        break;
        case "身体得分":
          bdinfoarry.body_score=bdinfo[index].num
        break;
        case "身体年龄":
          bdinfoarry.physical_age=bdinfo[index].num
        break;
        case "标准体重":
          bdinfoarry.standard_weight=bdinfo[index].num
          bdinfoarry.standard_weight_r=bdinfo[index].level
          bdinfoarry.standard_weight_u=bdinfo[index].unit
        break;
        case "脂肪量":
          bdinfoarry.fat_num=bdinfo[index].num
          bdinfoarry.fat_num_r=bdinfo[index].level
          bdinfoarry.fat_num_u=bdinfo[index].unit
        break;
      }
    }
    bdinfoarry.productId=sdk.productId,
    bdinfoarry.deviceName=sdk.deviceName,
    bdinfoarry.wx_unionid=myuserInfo.UserID
    bdinfoarry.impedance=parseInt(jxstate.body_r_enc)
    bdinfoarry.c_time=(moment(current_time).valueOf()),
    bdinfoarry.user_height=userinfo.height,
    bdinfoarry.user_weight=parseFloat(jxstate.weight).toFixed(2),
    bdinfoarry.user_weight_u=parseInt(jxstate.weight_unit),
    console.log(bdinfoarry)
    PubSub.publish('bdinfoarry',bdinfoarry)
  }
  else{
    Toast.fail("获取信息失败，请确保您已录入体重、身高、年龄！")
  }
}
// 传入最后一次数据，实时计算出体脂数据
function getlastbdinfo(userinfo,hexString){
  console.log("getlastbdinfo-userinfo")
  console.log(userinfo)
  var age = matAge(parseInt(userinfo.birthday),parseInt(current_time))
  var request = require('superAgent')
  request
  .post("http://lx.yodatech.cn/app/user/body/params")
  .send({
    "age": age,
    "appid": APPID,
    "height": userinfo.height,
    "hexString": hexString,
    "nonce": randomNum(1,2048),
    "scaleType": 1,//体脂秤类型 1：四极秤 2：八极秤, 默认：1 四极秤
    "sex": userinfo.sex,
    "signature": signature,
    "timeStamp": new Date().valueOf()
  })
  .end(function(err, res){
    console.log("getlastbdinfo")
    console.log(res)
    if(res.code = 1000){
      var result = res.body
      console.log(result)
      if(result.code == 1){
        let bdinfo = result.data.data.obj
        console.log("传入最后一次数据，实时从乐福计算出体脂数据")
        console.log(bdinfo)
        if(bdinfo != null){
          console.log(bdinfo)
          PubSub.publish('lefuData',bdinfo)
        }
        else{
          Toast.fail("获取信息失败，请确保您已录入体重、身高、年龄！")
        }
      }
    }
    else{
      console.log('服务器出错'+res)
    }
  })
}
// 通过ID获取三方用户数据
const getThirdUserInfo =(id) =>{
  return new Promise(function (resolve, reject) {
    var request = require('superAgent')
    request
    .post(APIURL+'getThirdUserInfo')
    .send({
      "productId":sdk.productId,
      "deviceName":sdk.deviceName,
      "thirdUserId":id,
      "wx_unionid":myuserInfo.UserID,
    })
    .end(function(err, res){
      if(res.body.code == 1){
        var userinfo = res.body.data.third_user
        console.log('获取三方用户数据如下：')
        console.log(userinfo)
        resolve(userinfo);
      }else{
        console.log('服务器出错'+res)
        reject(new Error(res.body));
      }
    })
});
}
// 单位为LB时对小数点的处理
function formatDecimal(num, decimal) {
  num = num.toString()
  let index = num.indexOf('.')
  if (index !== -1) {
    num = num.substring(0, decimal + index + 1)
  } else {
    num = num.substring(0)
  }
  return parseFloat(num).toFixed(decimal)
}
// 签名
const signature = () =>{
  let md5 = require('js-md5');
  let tme =  new Date().valueOf().toString();
  let nonce = randomNum(1,896154).toString()
  let tempSIGA = md5("nonce="+nonce+"timeStamp="+tme+""+APPSECRET).toUpperCase()
  console.log("签名:",tempSIGA)
  return tempSIGA
}
//生成从minNum到maxNum的随机数
function randomNum(minNum,maxNum){ 
  switch(arguments.length){ 
      case 1: 
          return parseInt(Math.random()*minNum+1,10); 
      break; 
      case 2: 
          return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
      break; 
          default: 
              return 0; 
          break; 
  } 
}